﻿using Microsoft.EntityFrameworkCore;

namespace DAL;

public class PageList<T>
{

    public PageList(List<T> items, int Count, int PageNumber, int PageSize)
    {
        this.PageNumber = PageNumber;
        this.PageSize = PageSize;
        Items = items;
        this.Count = Count;
        TotalItems = (int)Math.Ceiling((decimal)TotalItems / PageSize);
    }
    /// <summary>
    /// 集合的长度
    /// </summary>
    public int Count { get; set; }
    /// <summary>
    /// 页码
    /// </summary>
    public int PageNumber { get; set; }
    /// <summary>
    /// 当前页行数
    /// </summary>
    public int PageSize { get; set; }
    /// <summary>
    /// 总共分多少页
    /// </summary>
    public int TotalItems { get; set; }
    /// <summary>
    /// 当前集合
    /// </sum mary>
    public List<T> Items { get; set; }

    public static PageList<T> GetPageList(IQueryable<T> items, int pageNumber, int pageSize)
    {
        var count = items.Count();
        var pagedData = items.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
        var pageList = new PageList<T>(pagedData, count, pageNumber, pageSize);
        return pageList;
    }

    public static async Task<PageList<T>> GetPageListAsync(IQueryable<T> items, int pageNumber, int pageSize,CancellationToken cancellationToken=default)
    {
        var count = await items.CountAsync(cancellationToken);
        var pagedData = await items.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();
        var pageList = new PageList<T>(pagedData, count, pageNumber, pageSize);
        return pageList;
    }
}
